package com.penngo.gui.dfdiff.utils;


import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.CharsetUtil;
import info.monitorenter.cpdetector.io.*;
import org.fife.ui.rsyntaxtextarea.modes.*;
import javax.swing.*;
import javax.swing.filechooser.FileSystemView;
import java.awt.*;
import java.io.*;
import java.net.URL;
import java.net.URLDecoder;
import java.nio.charset.Charset;
import java.util.*;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class ToolUtil {
    private static final Logger log = LogUtils.getLogger(ToolUtil.class);
    private static List<Object> styleList;
    /**
     * 选在当前目录查找，再在包内查找。
     *
     * @return
     */
    public static InputStream getFileInputStream(String filename) throws FileNotFoundException {
        InputStream is = null;

        File file = new File(filename);
        if (file.exists() == true) {
            is = new FileInputStream(file);
            System.out.println("log.properties:" + file.getAbsolutePath());
        } else if (is == null) {
            URL url = ToolUtil.class.getProtectionDomain().getCodeSource().getLocation();
            String filePath = null;
            try {
                filePath = URLDecoder.decode(url.getPath(), "utf-8");// 转化为utf-8编码，支持中文
                File fileTemp = new File(filePath);
                if (fileTemp.isFile() == true) {
                    fileTemp = fileTemp.getParentFile();
                }
                file = new File(fileTemp, filename);
                is = new FileInputStream(file);
                System.out.println("log.properties=" + file.getAbsolutePath());
            } catch (Exception e) {
                System.out.println("warning " + filename + " not exist.");
            }

        }
        if (is == null) {
            // 保证nate-image下被编译
            System.out.println("log.properties@" + ToolUtil.class.getClassLoader().getResource("."));
            InputStream is2 = ToolUtil.class.getClassLoader().getResourceAsStream(filename);
            is = is2;
        }
        return is;
    }

    public static String getRunPath() {
        try {
            File path = new File(".");
            URL url = ToolUtil.class.getProtectionDomain().getCodeSource().getLocation();
            String filePath = URLDecoder.decode(url.getPath(), "utf-8");
            File fileTemp = new File(filePath);
            if (fileTemp.isFile() == true) {
                fileTemp = fileTemp.getParentFile();
            }
            return fileTemp.getAbsolutePath();
        } catch (Exception e) {
            System.out.println("RunPath path error=====:" + e.getMessage());
            e.printStackTrace();
        }
        return ".";
    }

    /**
     * 获得文件编码
     */
    public static String getFileCharset(File file){
        CodepageDetectorProxy detector = CodepageDetectorProxy.getInstance();
        detector.add(new ParsingDetector(false));
        detector.add(JChardetFacade.getInstance());
        detector.add(ASCIIDetector.getInstance());
        detector.add(UnicodeDetector.getInstance());
        Charset charset = null;
        try {
            charset = detector.detectCodepage(file.toURI().toURL());
        } catch (Exception e) {
            log.log(Level.SEVERE, "getFileCharset error======:" + file.getAbsolutePath() + "," + charset, e.getMessage());
        }
        String charsetName = null;//"UTF-8";
        if (charset != null) {
            if (charset.name().equals("US-ASCII")) {
                charsetName = "ISO_8859_1";
            } else if (charset.name().startsWith("UTF")) {
                charsetName = charset.name();
            }else if(charset.name().startsWith("GB")){
                charsetName="GBK";
            }
        }
        return charsetName;

    }

    public static String readString(File file){
        String str = null;
        String charset = ToolUtil.getFileCharset(file);
        try{
            str = FileUtil.readString(file, CharsetUtil.charset(charset));
        }
        catch(Exception e){
            log.log(Level.SEVERE, "readString error===" + charset + "," + file.getAbsolutePath(), e);
        }
        return str;
    }

    public static List<Object> getStyle(){
        styleList = Arrays.asList(
                "text/plain", List.of("txt"), PlainTextTokenMaker.class,
                "text/actionscript", List.of("as"), ActionScriptTokenMaker.class,
                "text/asm", List.of("asm"), AssemblerX86TokenMaker.class,
                "text/asm6502", null, Assembler6502TokenMaker.class,
                "text/bbcode", null, BBCodeTokenMaker.class,
                "text/c", List.of("c","h"), CTokenMaker.class,
                "text/clojure", List.of("clj"), ClojureTokenMaker.class,
                "text/cpp", List.of("cpp","hpp"), CPlusPlusTokenMaker.class,
                "text/cs", List.of(".cs","csx"),CSharpTokenMaker.class,
                "text/css", List.of("css"),CSSTokenMaker.class,
                "text/csv", List.of("csv"),CsvTokenMaker.class,
                "text/d", List.of("d"), DTokenMaker.class,
                "text/dockerfile", List.of("dockerfile"),DockerTokenMaker.class,
                "text/dart", List.of("dart"), DartTokenMaker.class,
                "text/delphi", null, DelphiTokenMaker.class,
                "text/dtd", null, DtdTokenMaker.class,
                "text/fortran", null, FortranTokenMaker.class,
                "text/golang", List.of("go"), GoTokenMaker.class,
                "text/groovy", List.of("groovy","gvy","gradle"), GroovyTokenMaker.class,
                "text/handlebars", null, HandlebarsTokenMaker.class,
                "text/hosts", List.of("hosts","host"), HostsTokenMaker.class,
                "text/htaccess", List.of("htaccess"), HtaccessTokenMaker.class,
                "text/html", List.of("html","vue"), HTMLTokenMaker.class,
                "text/ini", List.of("ini"), IniTokenMaker.class,
                "text/java", List.of("java"), JavaTokenMaker.class,
                "text/javascript", List.of("js"), JavaScriptTokenMaker.class,
                "text/json", List.of("json"), JsonTokenMaker.class,
                "text/jshintrc", null, JshintrcTokenMaker.class,
                "text/jsp", List.of("jsp"), JSPTokenMaker.class,
                "text/kotlin", List.of("kt"), KotlinTokenMaker.class,
                "text/latex", List.of("tex","ltx"), LatexTokenMaker.class,
                "text/less", null, LessTokenMaker.class,
                "text/lisp", null, LispTokenMaker.class,
                "text/lua", List.of("lua"), LuaTokenMaker.class,
                "text/makefile", List.of("make","makefile"), MakefileTokenMaker.class,
                "text/markdown", List.of("md"), MarkdownTokenMaker.class,
                "text/mxml", null, MxmlTokenMaker.class,
                "text/nsis", null, NSISTokenMaker.class,
                "text/perl", List.of("pl"), PerlTokenMaker.class,
                "text/php", List.of("php"), PHPTokenMaker.class,
                "text/proto", null, ProtoTokenMaker.class,
                "text/properties", List.of("properties","config"), PropertiesFileTokenMaker.class,
                "text/python", List.of("py"), PythonTokenMaker.class,
                "text/ruby", List.of("rb"), RubyTokenMaker.class,
                "text/sas", null, SASTokenMaker.class,
                "text/scala", List.of("scala","sbt"), ScalaTokenMaker.class,
                "text/sql", List.of("sql"), SQLTokenMaker.class,
                "text/tcl", null, TclTokenMaker.class,
                "text/typescript", List.of("ts"), TypeScriptTokenMaker.class,
                "text/unix", List.of("sh","bash"), UnixShellTokenMaker.class,
                "text/vb", List.of("vb"), VisualBasicTokenMaker.class,
                "text/bat", List.of("bat","cmd"), WindowsBatchTokenMaker.class,
                "text/xml", List.of("xml"), XMLTokenMaker.class,
                "text/yaml", List.of("yaml","yml"), YamlTokenMaker.class);
        return styleList;
    }

    @SuppressWarnings("unchecked")
    public static Map<String, List<String>> getFileExtension() {

        Map<String, List<String>> map = new TreeMap<>(Comparator.naturalOrder());

        List<Object> list = getStyle();
        for(int i = 0; i + 2 < list.size(); i = i + 3){
            Object extList = list.get(i + 1);
            if(extList != null){
                map.put((String)list.get(i), (List<String>)extList);
            }
        }
        return map;
    }


    public Font getFont(){
        Font font1 = null;
        try{
            String fontname = "D:\\project\\idea\\datagui\\DFDiff\\logs\\zhenhei.TTF";
            Font font = Font.createFont(Font.TRUETYPE_FONT, new File(fontname));
            font1 = font.deriveFont(Font.BOLD, 16);
        }
        catch(Exception e){
            e.printStackTrace();
        }
        return font1;
    }

    public static boolean isWindow(){
        String os = System.getProperty("os.name");
        //Windows操作系统
        if (os != null && os.toLowerCase().startsWith("windows")) {
            return true;
        }
        return false;
    }
    public static boolean isMac(){
        String os = System.getProperty("os.name");
        //Mac操作系统
        if (os != null && os.toLowerCase().startsWith("mac")) {
            return true;
        }
        return false;
    }
    public static boolean isLinux(){
        String os = System.getProperty("os.name");
        //Linux操作系统
        if (os != null && os.toLowerCase().startsWith("linux")) {
            return true;
        }
        return false;
    }

    public static File getConfigDir(){
        //java.io.tmpdir=C:\Users\admin\AppData\Local\Temp\
        String tempdir = System.getProperty("java.io.tmpdir");
        File dir = new File(tempdir, "dfdiff");
        if(!dir.exists()){
            boolean mkdir = dir.mkdir();
            if(!mkdir){
                log.log(Level.WARNING, "=====mkdir error:" + dir.getAbsolutePath());
            }
        }
        return dir;
    }

    public static void initLookAndFeel() throws ClassNotFoundException, InstantiationException, IllegalAccessException, UnsupportedLookAndFeelException {

        //Windows操作系统
        if (ToolUtil.isWindow()) {
            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
        } else {
            //Linux或其它操作系统
            // linux中文输入兼容
            System.setProperty("jdk.gtk.version", "2");
            String lookAndFeel =UIManager.getCrossPlatformLookAndFeelClassName();
            UIManager.setLookAndFeel(lookAndFeel);
//                UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
            //UIManager.setLookAndFeel(NimbusLookAndFeel.class.getName());

            //1、Metal风格 (默认)
//                String lookAndFeel = "javax.swing.plaf.metal.MetalLookAndFeel";
//                UIManager.setLookAndFeel(lookAndFeel);

            //2、Windows风格
//                String lookAndFeel = "com.sun.java.swing.plaf.windows.WindowsLookAndFeel";
//                UIManager.setLookAndFeel(lookAndFeel);

            //Windows Classic风格
//                String lookAndFeel = "com.sun.java.swing.plaf.windows.WindowsClassicLookAndFeel";
//                UIManager.setLookAndFeel(lookAndFeel);

//                4、Motif风格
//                String lookAndFeel4 = "com.sun.java.swing.plaf.motif.MotifLookAndFeel";
//                UIManager.setLookAndFeel(lookAndFeel4);

//                5、Mac风格 (需要在相关的操作系统上方可实现)
//            String lookAndFeel5 = "com.sun.java.swing.plaf.mac.MacLookAndFeel";
//            UIManager.setLookAndFeel(lookAndFeel5);

//                6、GTK风格 (需要在相关的操作系统上方可实现)
//            String lookAndFeel6 = "com.sun.java.swing.plaf.gtk.GTKLookAndFeel";
//            UIManager.setLookAndFeel(lookAndFeel6);

//                7、可跨平台的默认风格
//            String lookAndFeel7 = UIManager.getCrossPlatformLookAndFeelClassName();
//            UIManager.setLookAndFeel(lookAndFeel7);

//                8、当前系统的风格
//            String lookAndFeel8 = UIManager.getSystemLookAndFeelClassName();
//            UIManager.setLookAndFeel(lookAndFeel8);

        }
    }

    public static Icon getSystemIcon(File file){
        Icon icon = FileSystemView.getFileSystemView().getSystemIcon(file);
        if(icon == null){
            icon = ImgUtil.IMAGE_FILE;
        }
        return icon;
    }


    public static void main(String[] args) throws Exception{
//        File file = new File("DFDiff\\target\\logs\\log9.log");
//        System.out.println(getFileCharset(file));
//        System.out.println(getCharset(file));
//        getFileExtension().forEach((k,v)->{
//            System.out.println(k + "," + v);
//        });

//        readXml2();
        // com,cn

    }

}
